"use client";

import * as React from "react";

import { type DropdownMenuProps } from "@radix-ui/react-dropdown-menu";

import { TablePlugin, useTableMergeState } from "@platejs/table/react";
import {
  ArrowDown,
  ArrowLeft,
  ArrowRight,
  ArrowUp,
  Combine,
  Grid3x3Icon,
  Table,
  Trash2Icon,
  Ungroup,
  XIcon,
} from "lucide-react";
import { KEYS } from "platejs";
import { useEditorPlugin, useEditorSelector } from "platejs/react";

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/plate/ui/dropdown-menu";
import { cn } from "@/lib/utils";

import { ToolbarButton } from "./toolbar";

export function TableToolbarButton(props: DropdownMenuProps) {
  const tableSelected = useEditorSelector(
    (editor) =&gt; editor.api.some({ match: { type: KEYS.table } }),
    [],
  );

  const { editor, tf } = useEditorPlugin(TablePlugin);
  const [open, setOpen] = React.useState(false);
  const mergeState = useTableMergeState();

  return (
    &lt;DropdownMenu open={open} onOpenChange={setOpen} modal={false} {...props}&gt;
      &lt;DropdownMenuTrigger asChild&gt;
        &lt;ToolbarButton pressed={open} tooltip="Table" isDropdown&gt;
          <table />
        &lt;/ToolbarButton&gt;
      &lt;/DropdownMenuTrigger&gt;

      &lt;DropdownMenuContent
        className="flex w-[180px] min-w-0 flex-col"
        align="start"
      &gt;
        &lt;DropdownMenuGroup&gt;
          &lt;DropdownMenuSub&gt;
            &lt;DropdownMenuSubTrigger className="gap-2 data-[disabled]:pointer-events-none data-[disabled]:opacity-50"&gt;
              &lt;Grid3x3Icon className="size-4" /&gt;
              <span>Table</span>
            &lt;/DropdownMenuSubTrigger&gt;
            &lt;DropdownMenuSubContent className="m-0 p-0"&gt;
              &lt;TablePicker /&gt;
            &lt;/DropdownMenuSubContent&gt;
          &lt;/DropdownMenuSub&gt;

          &lt;DropdownMenuSub&gt;
            &lt;DropdownMenuSubTrigger
              className="gap-2 data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
              disabled={!tableSelected}
            &gt;
              <div />
              <span>Cell</span>
            &lt;/DropdownMenuSubTrigger&gt;
            &lt;DropdownMenuSubContent&gt;
              &lt;DropdownMenuItem
                className="min-w-[180px]"
                disabled={!mergeState.canMerge}
                onSelect={() =&gt; {
                  tf.table.merge();
                  editor.tf.focus();
                }}
              &gt;
                &lt;Combine /&gt;
                Merge cells
              &lt;/DropdownMenuItem&gt;
              &lt;DropdownMenuItem
                className="min-w-[180px]"
                disabled={!mergeState.canSplit}
                onSelect={() =&gt; {
                  tf.table.split();
                  editor.tf.focus();
                }}
              &gt;
                &lt;Ungroup /&gt;
                Split cell
              &lt;/DropdownMenuItem&gt;
            &lt;/DropdownMenuSubContent&gt;
          &lt;/DropdownMenuSub&gt;

          &lt;DropdownMenuSub&gt;
            &lt;DropdownMenuSubTrigger
              className="gap-2 data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
              disabled={!tableSelected}
            &gt;
              <div />
              <span>Row</span>
            &lt;/DropdownMenuSubTrigger&gt;
            &lt;DropdownMenuSubContent&gt;
              &lt;DropdownMenuItem
                className="min-w-[180px]"
                disabled={!tableSelected}
                onSelect={() =&gt; {
                  tf.insert.tableRow({ before: true });
                  editor.tf.focus();
                }}
              &gt;
                &lt;ArrowUp /&gt;
                Insert row before
              &lt;/DropdownMenuItem&gt;
              &lt;DropdownMenuItem
                className="min-w-[180px]"
                disabled={!tableSelected}
                onSelect={() =&gt; {
                  tf.insert.tableRow();
                  editor.tf.focus();
                }}
              &gt;
                &lt;ArrowDown /&gt;
                Insert row after
              &lt;/DropdownMenuItem&gt;
              &lt;DropdownMenuItem
                className="min-w-[180px]"
                disabled={!tableSelected}
                onSelect={() =&gt; {
                  tf.remove.tableRow();
                  editor.tf.focus();
                }}
              &gt;
                &lt;XIcon /&gt;
                Delete row
              &lt;/DropdownMenuItem&gt;
            &lt;/DropdownMenuSubContent&gt;
          &lt;/DropdownMenuSub&gt;

          &lt;DropdownMenuSub&gt;
            &lt;DropdownMenuSubTrigger
              className="gap-2 data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
              disabled={!tableSelected}
            &gt;
              <div />
              <span>Column</span>
            &lt;/DropdownMenuSubTrigger&gt;
            &lt;DropdownMenuSubContent&gt;
              &lt;DropdownMenuItem
                className="min-w-[180px]"
                disabled={!tableSelected}
                onSelect={() =&gt; {
                  tf.insert.tableColumn({ before: true });
                  editor.tf.focus();
                }}
              &gt;
                &lt;ArrowLeft /&gt;
                Insert column before
              &lt;/DropdownMenuItem&gt;
              &lt;DropdownMenuItem
                className="min-w-[180px]"
                disabled={!tableSelected}
                onSelect={() =&gt; {
                  tf.insert.tableColumn();
                  editor.tf.focus();
                }}
              &gt;
                &lt;ArrowRight /&gt;
                Insert column after
              &lt;/DropdownMenuItem&gt;
              &lt;DropdownMenuItem
                className="min-w-[180px]"
                disabled={!tableSelected}
                onSelect={() =&gt; {
                  tf.remove.tableColumn();
                  editor.tf.focus();
                }}
              &gt;
                &lt;XIcon /&gt;
                Delete column
              &lt;/DropdownMenuItem&gt;
            &lt;/DropdownMenuSubContent&gt;
          &lt;/DropdownMenuSub&gt;

          &lt;DropdownMenuItem
            className="min-w-[180px]"
            disabled={!tableSelected}
            onSelect={() =&gt; {
              tf.remove.table();
              editor.tf.focus();
            }}
          &gt;
            &lt;Trash2Icon /&gt;
            Delete table
          &lt;/DropdownMenuItem&gt;
        &lt;/DropdownMenuGroup&gt;
      &lt;/DropdownMenuContent&gt;
    &lt;/DropdownMenu&gt;
  );
}

function TablePicker() {
  const { editor, tf } = useEditorPlugin(TablePlugin);

  const [tablePicker, setTablePicker] = React.useState({
    grid: Array.from({ length: 8 }, () =&gt; Array.from({ length: 8 }).fill(0)),
    size: { colCount: 0, rowCount: 0 },
  });

  const onCellMove = (rowIndex: number, colIndex: number) =&gt; {
    const newGrid = [...tablePicker.grid];

    for (let i = 0; i &lt; newGrid.length; i++) {
      for (let j = 0; j &lt; newGrid[i]!.length; j++) {
        newGrid![i]![j] =
          i &gt;= 0 && i &lt;= rowIndex && j &gt;= 0 && j &lt;= colIndex ? 1 : 0;
      }
    }

    setTablePicker({
      grid: newGrid,
      size: { colCount: colIndex + 1, rowCount: rowIndex + 1 },
    });
  };

  return (
    <div> {
        tf.insert.table(tablePicker.size, { select: true });
        editor.tf.focus();
      }}
    &gt;
      <div>
        {tablePicker.grid.map((rows, rowIndex) =&gt;
          rows.map((value, columIndex) =&gt; {
            return (
              <div> {
                  onCellMove(rowIndex, columIndex);
                }}
              /&gt;
            );
          }),
        )}
      </div>

      <div>
        {tablePicker.size.rowCount} x {tablePicker.size.colCount}
      </div>
    </div>
  );
}
